/**
 * 用户相关Mock数据
 */

import { generateId, generateToken, formatDate } from '../utils'

// 模拟用户数据
const mockUsers = [
  {
    id: '1',
    username: 'demo_user',
    email: 'demo@example.com',
    nickname: '演示用户',
    avatar: 'https://via.placeholder.com/100x100?text=Avatar',
    phone: '13800138000',
    gender: 'male',
    birthday: '1990-01-01',
    bio: '这是一个演示用户账号',
    location: '北京市',
    website: 'https://example.com',
    createdAt: '2024-01-01T00:00:00.000Z',
    updatedAt: '2024-01-01T00:00:00.000Z'
  }
]

// 当前登录用户
let currentUser = null
let currentToken = null

export default {
  // 用户登录
  'POST /auth/login': async (data) => {
    const { username, password } = data
    
    // 简单验证
    if (!username || !password) {
      throw new Error(JSON.stringify({ code: 1001, message: '用户名和密码不能为空' }))
    }
    
    // 查找用户
    const user = mockUsers.find(u => u.username === username || u.email === username)
    if (!user) {
      throw new Error(JSON.stringify({ code: 1002, message: '用户名或密码错误' }))
    }
    
    // 模拟密码验证（实际开发中应该使用加密验证）
    if (password !== '123456') {
      throw new Error(JSON.stringify({ code: 1002, message: '用户名或密码错误' }))
    }
    
    // 生成token
    const token = generateToken()
    currentUser = user
    currentToken = token
    
    return {
      token,
      user: {
        id: user.id,
        username: user.username,
        email: user.email,
        nickname: user.nickname,
        avatar: user.avatar
      },
      expiresIn: 7200 // 2小时
    }
  },
  
  // 用户注册
  'POST /auth/register': async (data) => {
    const { username, email, password, nickname } = data
    
    // 验证必填字段
    if (!username || !email || !password) {
      throw new Error(JSON.stringify({ code: 1001, message: '用户名、邮箱和密码不能为空' }))
    }
    
    // 检查用户名是否已存在
    if (mockUsers.find(u => u.username === username)) {
      throw new Error(JSON.stringify({ code: 1004, message: '用户名已存在' }))
    }
    
    // 检查邮箱是否已存在
    if (mockUsers.find(u => u.email === email)) {
      throw new Error(JSON.stringify({ code: 1004, message: '邮箱已存在' }))
    }
    
    // 创建新用户
    const newUser = {
      id: generateId(),
      username,
      email,
      nickname: nickname || username,
      avatar: 'https://via.placeholder.com/100x100?text=' + (nickname || username).charAt(0),
      phone: '',
      gender: '',
      birthday: '',
      bio: '',
      location: '',
      website: '',
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString()
    }
    
    mockUsers.push(newUser)
    
    return {
      id: newUser.id,
      username: newUser.username,
      email: newUser.email,
      nickname: newUser.nickname,
      avatar: newUser.avatar
    }
  },
  
  // 获取用户信息
  'GET /user/info': async () => {
    if (!currentUser || !currentToken) {
      throw new Error(JSON.stringify({ code: 1002, message: '未登录或token已过期' }))
    }
    
    return {
      ...currentUser,
      // 不返回敏感信息
      password: undefined
    }
  },
  
  // 更新用户信息
  'PUT /user/info': async (data) => {
    if (!currentUser || !currentToken) {
      throw new Error(JSON.stringify({ code: 1002, message: '未登录或token已过期' }))
    }
    
    // 更新用户信息
    const allowedFields = ['nickname', 'avatar', 'phone', 'gender', 'birthday', 'bio', 'location', 'website']
    const updates = {}
    
    allowedFields.forEach(field => {
      if (data[field] !== undefined) {
        updates[field] = data[field]
      }
    })
    
    // 更新当前用户
    Object.assign(currentUser, updates, { updatedAt: new Date().toISOString() })
    
    // 更新用户列表中的数据
    const userIndex = mockUsers.findIndex(u => u.id === currentUser.id)
    if (userIndex !== -1) {
      mockUsers[userIndex] = { ...currentUser }
    }
    
    return {
      ...currentUser,
      password: undefined
    }
  },
  
  // 修改密码
  'POST /user/change-password': async (data) => {
    if (!currentUser || !currentToken) {
      throw new Error(JSON.stringify({ code: 1002, message: '未登录或token已过期' }))
    }
    
    const { oldPassword, newPassword } = data
    
    if (!oldPassword || !newPassword) {
      throw new Error(JSON.stringify({ code: 1001, message: '旧密码和新密码不能为空' }))
    }
    
    // 验证旧密码（实际开发中应该使用加密验证）
    if (oldPassword !== '123456') {
      throw new Error(JSON.stringify({ code: 1001, message: '旧密码错误' }))
    }
    
    // 模拟密码更新
    return {
      message: '密码修改成功'
    }
  },
  
  // 用户登出
  'POST /auth/logout': async () => {
    currentUser = null
    currentToken = null
    
    return {
      message: '登出成功'
    }
  },
  
  // 刷新token
  'POST /auth/refresh-token': async () => {
    if (!currentUser || !currentToken) {
      throw new Error(JSON.stringify({ code: 1002, message: '未登录或token已过期' }))
    }
    
    // 生成新token
    const newToken = generateToken()
    currentToken = newToken
    
    return {
      token: newToken,
      expiresIn: 7200 // 2小时
    }
  }
}